package com.jjh.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jjh.consts.Result;
import com.jjh.controller.FileController;
import com.jjh.mapper.CategoryMapper;
import com.jjh.mapper.DishMapper;
import com.jjh.mapper.FlavourTagMapper;
import com.jjh.pojo.Category;
import com.jjh.pojo.Dish;
import com.jjh.pojo.User;
import com.jjh.pojo.vo.DishVo;
import com.jjh.pojo.vo.FlavourTagStrVo;
import com.jjh.pojo.vo.FlavourTagVo;
import com.jjh.service.DishService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;
    @Resource
    private FlavourTagMapper flavourTagMapper;
    @Resource
    private CategoryMapper categoryMapper;

    @Value("${img.dishImgPath}")
    private String dishImgPath;

    @Override
    public Result page(Integer page, Integer size, Map<String, Object> map) {

        PageHelper.startPage(page,size);
        List<Dish> dishes = getByCondition(map);
        PageInfo<Dish> pageInfo = new PageInfo<>(dishes);
        return Result.ok(pageInfo);


    }


    @Override
    public List<Dish> getByCondition(Map<String, Object> map) {
        return dishMapper.getByCondition(map);
    }

    /**
     * 添加菜品
     * @param dishVo
     * @return
     */
    @Override
    public Result addDish(DishVo dishVo) throws JsonProcessingException {

        String name = dishVo.getName();
        if(ObjectUtils.isEmpty(name)){
            return Result.error("菜品名称不能为空！");
        }
        String img = dishVo.getImg();
        if(ObjectUtils.isEmpty(img)){
            return Result.error("菜品图片不能为空!");
        }
        Double price = dishVo.getPrice();
        if(ObjectUtils.isEmpty(price)){
            return Result.error("价格不能为空!");
        }
        if(price<=0){
            return Result.error("价格不能小于0");
        }
        String status = dishVo.getStatus();
        if(ObjectUtils.isEmpty(status)){
            return Result.error("菜品状态不能为空");
        }
        if(  !"在售".equals(status)&&!"停售".equals(status)){
            return Result.error("菜品状态非法");
        }
        String category = dishVo.getCategory();
        if(ObjectUtils.isEmpty(category)){
            return Result.error("菜品分类不能为空");
        }
        List<FlavourTagVo> flavourTags = dishVo.getFlavourTags();
        if(ObjectUtils.isEmpty(flavourTags)){
            return Result.error("口味不能为空");
        }

        //先查询看看有没有该菜品
        Dish dish1 = dishMapper.getByDishName(name);
        if(!ObjectUtils.isEmpty(dish1)){
            return Result.error("已经存在该菜品！");
        }
        //通过传来的菜品分类名称查询分类id
        Category category1 = categoryMapper.getByName(category);
        if(ObjectUtils.isEmpty(category1)){
            return Result.error("没有该菜品分类");
        }
        //获取菜品分类id
        //构造dish对象
        Dish dish = new Dish();
        dish.setName(name);
        dish.setImg(img);
        dish.setCategory(category);
        dish.setCategoryId(category1.getId());
        dish.setDescription(dishVo.getDescription());
        dish.setStatus(status);
        dish.setPrice(price);
        //添加dish信息

        dishMapper.insert(dish);
        //添加flavourTags信息
        //对标签列表进行修改
        ObjectMapper objectMapper = new ObjectMapper();
        List<FlavourTagStrVo> flavourTagStrVoList = new ArrayList<>();
        for (FlavourTagVo flavourTag : flavourTags) {
            List<String> tag = flavourTag.getTag();
            String s = objectMapper.writeValueAsString(tag);
            FlavourTagStrVo flavourTagStrVo = new FlavourTagStrVo();
            BeanUtils.copyProperties(flavourTag,flavourTagStrVo,"tags");
            flavourTagStrVo.setDishId(dish.getId());
            flavourTagStrVo.setTags(s);
            flavourTagStrVo.setCreateTime(LocalDateTime.now());
            flavourTagStrVo.setUpdateTime(LocalDateTime.now());
            flavourTagStrVoList.add(flavourTagStrVo);
        }
        //批量添加
       int rows =  flavourTagMapper.addBatch(flavourTagStrVoList,dish.getId());

        if(rows>0){
            return Result.ok("添加成功!");
        }else {
            return Result.error("添加失败");
        }
    }

    @Override
    public Result changeStatus(Integer id,Integer status) {
        if(status!=0&&status!=1) {
            return Result.error("状态非法");
        }
       int row = dishMapper.updateStatus(id,status==1?"在售":"停售");
        if(row>0){
            return Result.ok("变更状态成功!");
        }else {
            log.error("修改菜品状态失败！{}","id:"+id+"status"+status);
            return Result.error("变更状态成功!");
        }
    }

    @Override
    public Result getDishInfo(Integer id) {

        //先查询菜品
       Dish dish = dishMapper.getById(id);
       //在查询口味标签
       List<FlavourTagStrVo> flavourTagStrVoList =  flavourTagMapper.getListByDishId(id);
       //封装到map集合中
        Map<String,Object> map = new HashMap<>();
        map.put("dish",dish);
        map.put("flavourTags",flavourTagStrVoList);

        return Result.ok(map);
    }

    /**
     * 修改菜品
     * @param dishVo
     * @return
     */
    @Override
    public Result updateDish(DishVo dishVo) throws JsonProcessingException {
        Integer id = dishVo.getId();
        if(ObjectUtils.isEmpty(id)){
            return Result.error("菜品id不能为空");
        }

        String name = dishVo.getName();
        if(ObjectUtils.isEmpty(name)){
            return Result.error("菜品名称不能为空！");
        }
        String img = dishVo.getImg();
        if(ObjectUtils.isEmpty(img)){
            return Result.error("菜品图片不能为空!");
        }
        Double price = dishVo.getPrice();
        if(ObjectUtils.isEmpty(price)){
            return Result.error("价格不能为空!");
        }
        if(price<=0){
            return Result.error("价格不能小于0");
        }
        String status = dishVo.getStatus();
        if(ObjectUtils.isEmpty(status)){
            return Result.error("菜品状态不能为空");
        }
        if(  !"在售".equals(status)&&!"停售".equals(status)){
            return Result.error("菜品状态非法");
        }
        String category = dishVo.getCategory();
        if(ObjectUtils.isEmpty(category)){
            return Result.error("菜品分类不能为空");
        }
        List<FlavourTagVo> flavourTags = dishVo.getFlavourTags();
        if(ObjectUtils.isEmpty(flavourTags)){
            return Result.error("口味不能为空");
        }
        //先查询看看有没有该菜品
        Dish dish1 = dishMapper.getByDishName(name);
        if(!ObjectUtils.isEmpty(dish1)&& !Objects.equals(dish1.getId(), id)){
            return Result.error("已经存在该菜品！");
        }
        //根据菜品分类名称查询菜品分类为了获取菜品分类id
        Category category1 = categoryMapper.getByName(category);
        if(ObjectUtils.isEmpty(category1)){
            return Result.error("没有该菜品分类");
        }

        //构造dish对象
        Dish dish = new Dish();
        dish.setId(id);
        dish.setName(name);
        dish.setImg(img);
        dish.setCategory(category);
        dish.setCategoryId(category1.getId());
        dish.setDescription(dishVo.getDescription());
        dish.setStatus(status);
        dish.setPrice(price);
        //添加dish信息


        //看看图片是否不一样，如果不一样，就要删除原来的图片
//        if(!dish1.getImg().equals(img)&& Objects.equals(dish1.getId(), id)){
//            //删除图片
//            FileController.deleteImg(img,dishImgPath);
//        }
        //可以修改了
        dishMapper.updateByPrimaryKey(dish);
        //添加flavourTags信息
        //对标签列表进行修改
        ObjectMapper objectMapper = new ObjectMapper();

        for (FlavourTagVo flavourTag : flavourTags) {
            List<String> tag = flavourTag.getTag();
            String s = objectMapper.writeValueAsString(tag);
            FlavourTagStrVo flavourTagStrVo = new FlavourTagStrVo();
            BeanUtils.copyProperties(flavourTag,flavourTagStrVo,"tags");
            flavourTagStrVo.setId(flavourTag.getId());
            flavourTagStrVo.setDishId(dish.getId());
            flavourTagStrVo.setTags(s);
            flavourTagStrVo.setCreateTime(LocalDateTime.now());
            flavourTagStrVo.setUpdateTime(LocalDateTime.now());
            //修改
            flavourTagMapper.updateById(flavourTagStrVo);
        }
        return Result.ok("修改成功");
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Override
    public Result deleteDishes(List<Integer> ids) {

        if(ObjectUtils.isEmpty(ids)){
            return Result.error("ids为空!");
        }
        //1.先查询出来菜品
        for (Integer id : ids) {
            Dish dish = dishMapper.getById(id);
            //然后获取图片
            String img = dish.getImg();
            //先删除对应的口味标签列表
            flavourTagMapper.deleteByDishId(id);
            //然后删除图片
            FileController.deleteImg(img,dishImgPath);
            //最后删除菜品信息
            dishMapper.deleteByPrimaryKey(id);
        }

        return Result.ok("删除成功！");
    }

    /**
     * 根据分类查询所有的菜品列表
     * @param cateId 菜品分类id
     * @return 菜品集合
     */
    @Override
    public Result getByCateId(Integer cateId) {
         List<Dish> dishList =  dishMapper.getByCateId(cateId);
         return Result.ok(dishList);
    }
}
